﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using SYSoft.Comm;
using SYSoft.Model;
using SYSoft.Model.Models.DeviceManage;
using SYSoft.Model.ViewModels.DeviceManage.Config;
using SYSoft.Services.DeviceManage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace SYSoft.Controllers.DeviceManage
{
    public class DeviceConfigController : BaseController
    {
        IDeviceEnergyConfigServices deviceEnergyConfigServices;
        IDevicePassConfigServices devicePassConfigServices;
        public DeviceConfigController(IDeviceEnergyConfigServices deviceEnergyConfigServices, IDevicePassConfigServices devicePassConfigServices)
        {
            this.deviceEnergyConfigServices = deviceEnergyConfigServices;
            this.devicePassConfigServices = devicePassConfigServices;
        }


        /// <summary>
        /// 获取能耗配置表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<List<DeviceEnergyConfig>>> GetEnergyList()
        {

            var model = await this.deviceEnergyConfigServices.Query();
            if (model != null && model.Count > 0)
            {
                return MessageModel.CreateSuccessResult(model);
            }
            return MessageModel.CreateFailedResult<List<DeviceEnergyConfig>>("");
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<MessageModel> EnergyUpdate([FromBody] DeviceEnergyConfig model)
        {
            var res = await deviceEnergyConfigServices.Update(model);
            if (res)
                return MessageModel.CreateSuccessResult<string>("sucess");
            return MessageModel.CreateFailedResult<string>("修改失败！！");
        }


        /// <summary>
        /// 获取通道配置表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<List<DevicePassConfig>>> GetPassList()
        {
            var model = await this.devicePassConfigServices.Query("","DeviceId");
            if (model != null && model.Count > 0)
            {
                return MessageModel.CreateSuccessResult(model);
            }
            return MessageModel.CreateFailedResult<List<DevicePassConfig>>("");
        }


        /// <summary>
        /// 添加通道配置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel> PassAdd(DevicePassConfig model)
        {
            var res = await this.devicePassConfigServices.Add(model);
            if (res > 0)
            {
                return MessageModel.CreateSuccessResult();
            }
            return new MessageModel("添加失败");
        }



        [HttpPut]
        public async Task<MessageModel> PassUpdate([FromBody] DevicePassConfig model)
        {
            var res = await devicePassConfigServices.Update(model);
            if (res)
                return MessageModel.CreateSuccessResult<string>("sucess");
            return MessageModel.CreateFailedResult<string>("修改失败！！");
        }


        /// <summary>
        /// 获取各种标准配置参数的配置表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public MessageModel GetStandardConfigList()
        {
            List<StandardConfigVM> vMs = new List<StandardConfigVM>();
            vMs.Add(new StandardConfigVM { ConfigProperty = "RunStatusCurrent", ConfigDescription = "电流运行状态", ConfigValue = ServerInfo.RunStatusCurrent.ToString() });
            vMs.Add(new StandardConfigVM { ConfigProperty = "EnnrgyStandard", ConfigDescription = "电能标准值", ConfigValue = ServerInfo.EnnrgyStandard.ToString() });
            vMs.Add(new StandardConfigVM { ConfigProperty = "GasnnrgyStandard", ConfigDescription = "天然气消耗标准值", ConfigValue = ServerInfo.GasnnrgyStandard.ToString() });
           // vMs.Add(new StandardConfigVM { ConfigProperty = "UnitEnnrgyStandard", ConfigDescription = "AR气体设定量", ConfigValue = ServerInfo.UnitEnnrgyStandard.ToString() });
            vMs.Add(new StandardConfigVM { ConfigProperty = "ARSetting", ConfigDescription = "AR气体设定量", ConfigValue = ServerInfo.ARSetting.ToString() });
            vMs.Add(new StandardConfigVM { ConfigProperty = "CO2Setting", ConfigDescription = "CO2气设定量", ConfigValue = ServerInfo.CO2Setting.ToString() });
            vMs.Add(new StandardConfigVM { ConfigProperty = "GasSetting", ConfigDescription = "天然气设定量", ConfigValue = ServerInfo.GasSetting.ToString() });

            string[] strs = new string[] { "等离子", "埋弧焊", "预拱", "自动焊", "剪折线", "机器人", "抛丸机", "油漆线", "组焊", "翻转机" };
            for (int i = 0; i < strs.Length; i++)
            {
                vMs.Add(new StandardConfigVM { ConfigProperty = $"AllUnitEnnrgyStandard_{i}", ConfigDescription = $"{strs[i]}单节标准能耗", ConfigValue = ServerInfo.AllUnitEnnrgyStandard[i].ToString() });
            }
                      
            return MessageModel.CreateSuccessResult(vMs);

        }


        /// <summary>
        /// 设置各种标准配置参数
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public MessageModel UpdateStandardConfig([FromBody] StandardConfigVM model)
        {
            return setPalmKey(model.ConfigProperty,Convert.ToSingle(model.ConfigValue));
        }


        //动态链接库中ClsPublic类有一变量 private static string key="1111";
        //下面通过反射的技术修改和获取值
        //设置key 
        private  MessageModel setPalmKey(string key, float value)
        {
            try
            {
                if (key.Contains("AllUnitEnnrgyStandard"))
                {
                   var list = key.Split("_");
                    ServerInfo.AllUnitEnnrgyStandard[Convert.ToInt32(list[1])] = value;
                }
                else
                {
                    Type type = typeof(ServerInfo);
                    BindingFlags flag = BindingFlags.Public | BindingFlags.Static;
                    FieldInfo f_key = type.GetField(key, flag);
                    f_key.SetValue(type, value);

                    if(key== "GasSetting")
                    {
                        var res4 = NetFactory.redisPool.ReadHashKey("MTCD:ConstGateWay", DeviceID.天然气站.ToString());
                        if (res4.IsSuccess)
                        {
                            JObject jObject = JObject.Parse(res4.Content);
                            if (jObject.Value<bool>("IsActive"))
                            {
                                float TotalVolume = Convert.ToSingle(jObject["TotalVolume"]);
                                NetFactory.redisPool.WriteKey("MTCD:STAT:FristTianranqi", TotalVolume.ToString());
                            }
                        }
                    }

                    if (key == "ARSetting" )
                    {
                        var res3 = NetFactory.redisPool.ReadHashKey("MTCD:ConstGateWay", DeviceID.混合气站.ToString());
                        if (res3.IsSuccess)
                        {
                            JObject jObject = JObject.Parse(res3.Content);
                            if (jObject.Value<bool>("IsActive"))
                            {
                                float TotalVolume = Convert.ToSingle(jObject["ActruellyUsed"]);
                                NetFactory.redisPool.WriteKey("MTCD:STAT:FristHunheqi_AR", TotalVolume.ToString());
                            }
                        }
                    }
                    if (key == "CO2Setting")  
                    {
                        var res3 = NetFactory.redisPool.ReadHashKey("MTCD:ConstGateWay", DeviceID.混合气站.ToString());
                        if (res3.IsSuccess)
                        {
                            JObject jObject = JObject.Parse(res3.Content);
                            if (jObject.Value<bool>("IsActive"))
                            {
                                float TotalVolume = Convert.ToSingle(jObject["ActruellyUsed"]);
                                NetFactory.redisPool.WriteKey("MTCD:STAT:FristHunheqi_CO2", TotalVolume.ToString());
                            }
                        }
                    }
                }               
                var res = ServerInfo.saveConfig();
                if (!res.IsSuccess)
                    return new MessageModel(res.Message);
                return MessageModel.CreateSuccessResult(); 
            }
            catch (Exception ex)
            {
                return new MessageModel(ex.Message);
            }
            
        }

        /// <summary>
        /// 获取key
        /// </summary>
        /// <returns></returns>
        private  object getPalmKey(string key)
        {
            Type type = typeof(ServerInfo);
            BindingFlags flag = BindingFlags.Public | BindingFlags.Static;
            FieldInfo f_key = type.GetField(key, flag);
            return f_key.GetValue(type);
        }




        // 设备远程控制###############################################################################################


        /// <summary>
        /// 设备远程控制
        /// </summary>
        ///// <returns></returns>
        //[HttpPost]
        //public MessageModel SetSwitch(int deviceid,int passindex,int status)
        //{
           
        //}

    }
}
